package com.ccb.jyzx.expand.ouapi.job;

import com.alibaba.fastjson.JSON;
import com.ccb.jyzx.expand.ouapi.beans.sync.DepartmentInfoSync;
import com.ccb.jyzx.expand.ouapi.service.DepartmentService;
import com.ccb.jyzx.expand.ouapi.service.report.ReportDepartmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author XIEFEI
 * @date 2019-11-14 9:29
 * @Description 部门信息同步任务
 **/
@Component
public class DepartmentSynchronizationJob {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${db_sync_switch}")
    public boolean db_sync_switch;

    @Autowired
    DepartmentService departmentService;

    @Autowired
    ReportDepartmentService reportDepartmentService;

    @Scheduled(cron = "0 0 0/2 * * ?")
    public void syncJob() {

        if (!db_sync_switch){
            return;
        }

        logger.info("开始同步部门信息任务====>");

        logger.info("读取ouapi数据库部门信息====>");
        List<DepartmentInfoSync> ouapi= departmentService.getAllSync();
        ConcurrentHashMap ohm = new ConcurrentHashMap(ouapi.size());
        if (ouapi!=null&&!ouapi.isEmpty()){
            ouapi.forEach(d->{
                byte[] bytes = JSON.toJSONBytes(d);
                String md5 = DigestUtils.md5DigestAsHex(bytes);
                ohm.put(d.getId(),md5);//存md5为Value,ID值为Key
            });
        }
        logger.info("读取了ouapi数据库部门信息: "+ohm.size()+" 条记录");

        logger.info("读取report_mode数据库部门信息====>");
        List<DepartmentInfoSync> report = reportDepartmentService.getAllSync();
        ConcurrentHashMap rhm = new ConcurrentHashMap(report.size());
        if (report!=null&&!report.isEmpty()){
            report.forEach(d->{
                byte[] bytes = JSON.toJSONBytes(d);
                String md5 = DigestUtils.md5DigestAsHex(bytes);
                rhm.put(d.getId(),md5);//存md5为Value,ID值为Key
            });
        }
        logger.info("读取了report_mode数据库部门信息: "+rhm.size()+" 条记录");

        //开始对比
        List<String> add=new ArrayList<>();//增加的记录ID
        List<String> modify=new ArrayList<>();//修改的记录ID
        List<String> delete=new ArrayList<>();//删除的记录ID

        if (report!=null&&!report.isEmpty()){
            rhm.forEach((id,md5)->{
                if (ohm.containsKey(id)){
                    if(!rhm.get(id).equals(ohm.get(id))){//如果md5不同,说明是修改了
                        modify.add(id.toString());
                    }
                }else {//如果是不包含,则说明是增加
                    add.add(id.toString());
                }
            });
            ohm.forEach((id,md5)->{
                if (!rhm.containsKey(id)){//如果不包含,则说明是减少的
                    delete.add(id.toString());
                }
            });
        }

        logger.info("部门信息对比结果: 增加了 "+add.size()+" 条记录");
        logger.info("部门信息对比结果: 更新了 "+modify.size()+" 条记录");
        logger.info("部门信息对比结果: 删除了 "+delete.size()+" 条记录");

        logger.info("开始同步部门表数据----");
        if (!add.isEmpty()){
          add.forEach(id->{
              report.stream().filter(d->{
                  return d.getId().equals(id);
              }).forEach(d->{
                  departmentService.insert(d);
              });
          });
        }
        if(!modify.isEmpty()){
            modify.forEach(id->{
                report.stream().filter(d->{
                    return d.getId().equals(id);
                }).forEach(d->{
                    departmentService.update(d);
                });
            });
        }
        if(!delete.isEmpty()){
            delete.forEach(id->{
                departmentService.deleteById(id);
            });
        }

        logger.info("结束同步部门信息任务====>");
    }


}
